package com.society.sgsc.dict.handler;

import com.github.pagehelper.PageHelper;
import com.society.sgsc.dict.service.DictService;
import com.society.sgsc.entities.Dict;
import com.society.sgsc.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * sgsc
 * com.society.sgsc.dict.handler
 * 字典控制器
 *
 * @author 尘心
 * @date 2025/3/14 下午 02:29
 */
@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/dict")
public class DictHandler {

    @Resource()
    DictService dictService;

    /**
     * 添加字典
     * @param dict 字典信息
     * @return CommonResult 统一返回信息
     */
    @PostMapping("/dict")
    public CommonResult<Dict> addDict(@RequestBody Dict dict) {
        try {
//            int i = dictService.saveDict(dict);
//            if (1 == i) {
//                return CommonResult.success(dict);
//            }
            return dictService.saveDict(dict) == 1 ? CommonResult.success(dict) : CommonResult.error(500, "添加失败,请重试……");
        } catch (Exception exception) {
            exception.printStackTrace();
            return CommonResult.error(500, "系统异常,请重试或联系管理员," + exception.getMessage());
        }
    }

    /**
     * 查询所有字典信息
     * @param pn 页码
     * @param size 每页条数
     * @return CommonResult 统一返回信息
     */
    @GetMapping("/dicts/{pn}/{size}")
    public CommonResult dicts(@PathVariable("pn") Integer pn, @PathVariable("size") Integer size) {
        try {
            PageHelper.startPage(pn, size);
            List<Dict> dicts = dictService.dicts();
            log.info("查询结果: {}", dicts);
            if(null == dicts){
                return  CommonResult.error(500, "暂无数据");
            }
            return CommonResult.success(dicts);
//            return  null == dictService.dicts() ? CommonResult.error(500, "暂无数据") : CommonResult.success(dictService.dicts());
        } catch (Exception exception) {
            exception.printStackTrace();
            return CommonResult.error(500, "系统异常,请重试或联系管理员," + exception.getMessage());
        }
    }
}
